package com.project.dao.impl;

import com.project.bean.UserBean;

import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class BaseDao {
    protected Connection con;//连接对象

    protected PreparedStatement ps;//sql语句执行对象

    protected ResultSet rs;//结果集

    /**
     * 建立连接
     */
    public void setConnection(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            this.con= DriverManager.getConnection("jdbc:mysql://localhost:6789/db?characterEncoding=utf-8"
            ,"root","lovo");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭连接
     */
    public void closeConnection(){
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List getObject(ResultSet rs) {

        ArrayList<Object> list = new ArrayList<>();
        this.rs = rs;
        try {
            while (this.rs.next()) {
                UserBean userBean = new UserBean();
                userBean.setId(this.rs.getInt("pk_userId"));
                userBean.setName(this.rs.getString("u_name"));
                userBean.setPassword(this.rs.getString("u_password"));
                userBean.setBirthday(LocalDate.parse(this.rs.getString("u_birthday")));
                list.add(userBean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
